<template>
  <div class="location-weather" :style="{ backgroundImage: `url(${backgroundURL})` }">
    <!-- 显示页面标题 -->
    <h1>天气预报系统</h1>
    
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="spinner"></div>
      <p>正在获取您的地理位置...</p>
    </div>
    
    <!-- 错误状态 -->
    <div v-else-if="error" class="error-container">
      <p>{{ error }}</p>
      <div class="search-container">
        <!-- 搜索输入框 -->
        <el-input
          v-model="searchCity"
          placeholder="请输入城市名称"
          suffix-icon="el-icon-search"
          @keyup.enter="searchWeather"
          style="width: 250px; margin-right: 10px;"
        ></el-input>
        <!-- 搜索按钮 -->
        <el-button type="primary" @click="searchWeather">搜索</el-button>
      </div>
      <div class="popular-cities">
        <p>热门城市：</p>
        <div class="city-tags">
          <!-- 热门城市标签 -->
          <el-tag
            v-for="city in popularCities"
            :key="city"
            @click="getWeatherByManualCity(city)"
            closable="false"
            effect="dark"
          >
            {{ city }}
          </el-tag>
        </div>
      </div>
    </div>
    
    <!-- 成功状态 -->
    <div v-else>
      <!-- 搜索框 -->
      <div class="search-container">
        <el-input
          v-model="searchCity"
          placeholder="请输入城市名称"
          suffix-icon="el-icon-search"
          @keyup.enter="searchWeather"
          style="width: 250px; margin-right: 10px;"
        ></el-input>
        <el-button type="primary" @click="searchWeather">搜索</el-button>
      </div>
      
      <p>您所在的城市: {{ city }}</p>
      
      <!-- 天气表格 -->
      <el-table :data="tableData" stripe style="width: 100%">
        <el-table-column prop="date" label="日期" width="120" />
        <el-table-column prop="week" label="星期几" width="120" />
        <el-table-column prop="dayweather" label="白天天气现象" width="120" />
        <el-table-column prop="nightweather" label="晚上天气现象" width="120" />
        <el-table-column prop="daytemp" label="白天温度" width="120" />
        <el-table-column prop="nighttemp" label="晚上温度" width="120" />
        <el-table-column prop="daywind" label="白天风向" width="120" />
        <el-table-column prop="nightwind" label="晚上风向" width="120" />
        <el-table-column prop="daypower" label="白天风力" width="120" />
        <el-table-column prop="nightpower" label="晚上风力" width="120" />
      </el-table>
      
      <!-- 气象灾害预警信息 -->
      <div v-if="warningList.length > 0" class="warning-container">
        <h2>气象灾害预警信息</h2>
        <!-- 循环显示预警信息 -->
        <el-alert
          v-for="(warning, index) in warningList"
          :key="index"
          :title="`${warning.warningType} - ${warning.warningLevel}`"
          :type="getWarningType(warning.warningLevel)"
          show-icon
          :closable="false"
          style="margin-bottom: 10px;"
        >
          <template #content>
            <p>{{ warning.warningContent }}</p>
            <p>发布时间: {{ warning.pubTime || '未知' }}</p>
          </template>
        </el-alert>
      </div>
      
      <!-- 无预警信息提示 -->
      <div v-else class="no-warning-container">
        <el-alert
          title="暂无气象灾害预警信息"
          type="success"
          show-icon
          style="margin-top: 20px;"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { getCityWeather, getWeatherWarning } from "../axios/home.js";

// 根据经纬度获取地址信息的异步函数
const getAddressByLocation = async (latitude, longitude, apiKey) => {
  try {
    const url = `https://restapi.amap.com/v3/geocode/regeo?key=${apiKey}&location=${longitude},${latitude}&extensions=base&output=json`;
    const response = await fetch(url);
    const data = await response.json();
    
    if (data.status === '1') {
      const addressComponent = data.regeocode.addressComponent;
      return addressComponent.city || addressComponent.province;
    } else {
      console.error('高德地图API错误:', data.info);
      return null;
    }
  } catch (error) {
    console.error('获取地址信息失败:', error);
    return null;
  }
};

// 定义响应式数据
const loading = ref(true);
const error = ref(null);
const city = ref("");
const tableData = ref([]);
const searchCity = ref('');
const popularCities = ref(['北京', '上海', '广州', '深圳', '杭州', '成都', '武汉', '重庆', '南京', '西安']);
const warningList = ref([]);
const backgroundURL = ref('https://picsum.photos/id/1018/1920/1080');
const isWarningLoading = ref(false);
const warningError = ref(null);

// 组件挂载后获取用户地理位置
onMounted(() => {
  getUserLocation();
});

// 获取用户地理位置
const getUserLocation = () => {
  if (navigator.geolocation) {
    // 使用浏览器的地理位置 API 获取用户位置
    navigator.geolocation.getCurrentPosition(
      handlePosition,
      handleError,
      { timeout: 15000, maximumAge: 300000 }
    );
  } else {
    // 浏览器不支持地理位置功能时显示错误信息
    error.value = "您的浏览器不支持地理位置功能。";
    loading.value = false;
  }
};

// 处理位置信息
const handlePosition = async (position) => {
  const latitude = position.coords.latitude;
  const longitude = position.coords.longitude;
  const apiKey = '8589ae5f4998a52d75ce6b23873072a7';
  
  // 根据经纬度获取城市名称
  city.value = await getAddressByLocation(latitude, longitude, apiKey);
  
  if (city.value) {
    try {
      // 获取天气数据
      const res = await getCityWeather(city.value);
      tableData.value = res.data.forecasts[0].casts;
      
      // 获取预警信息
      await fetchWarningInfo(city.value);
      
      loading.value = false;
    } catch (err) {
      // 获取天气信息失败时显示错误信息
      error.value = "获取天气信息失败。";
      loading.value = false;
    }
  } else {
    // 无法获取城市信息时显示错误信息
    error.value = "无法获取您所在的城市信息。";
    loading.value = false;
  }
};

// 处理位置错误
const handleError = (errorObj) => {
  // 根据错误代码显示不同的错误信息
  switch (errorObj.code) {
    case errorObj.PERMISSION_DENIED:
      error.value = "您拒绝了获取地理位置的请求。";
      break;
    case errorObj.POSITION_UNAVAILABLE:
      error.value = "地理位置信息不可用。";
      break;
    case errorObj.TIMEOUT:
      error.value = "请求地理位置超时。";
      break;
    case errorObj.UNKNOWN_ERROR:
      error.value = "发生未知错误。";
      break;
  }
  loading.value = false;
};

// 根据手动输入的城市名称获取天气数据
const getWeatherByManualCity = async (cityName) => {
  if (cityName) {
    loading.value = true;
    error.value = null;
    try {
      // 根据手动输入的城市名称获取天气数据
      const res = await getCityWeather(cityName);
      tableData.value = res.data.forecasts[0].casts;
      
      // 获取预警信息
      await fetchWarningInfo(cityName);
      
      city.value = cityName;
      loading.value = false;
    } catch (err) {
      // 获取天气信息失败时显示错误信息
      error.value = "获取天气信息失败。";
      loading.value = false;
    }
  }
};

// 获取预警信息的独立方法
const fetchWarningInfo = async (cityName) => {
  isWarningLoading.value = true;
  warningError.value = null;
  
  try {
    // 获取预警信息
    const warningRes = await getWeatherWarning(cityName);
    
    // 调试：打印API返回的数据
    console.log('预警API返回数据:', warningRes);
    
    // 根据不同API的返回结构调整
    if (warningRes.data.warning && warningRes.data.warning.length > 0) {
      // 假设API返回格式为 { warning: [{ type: '暴雨', level: '黄色', text: '...' }] }
      warningList.value = warningRes.data.warning.map(item => ({
        warningType: item.type || item.warningType || '未知类型',
        warningLevel: item.level || item.warningLevel || '未知级别',
        warningContent: item.text || item.warningContent || '暂无详细信息',
        pubTime: item.pubTime || '未知'
      }));
    } else if (warningRes.data.infos && warningRes.data.infos.length > 0) {
      // 保留原有的处理逻辑
      warningList.value = warningRes.data.infos.map(item => ({
        warningType: item.warningType || '未知类型',
        warningLevel: item.warningLevel || '未知级别',
        warningContent: item.warningContent || '暂无详细信息',
        pubTime: item.pubTime || '未知'
      }));
    } else {
      // 没有预警信息
      warningList.value = [];
    }
  } catch (error) {
    console.error('获取预警信息失败:', error);
    warningError.value = "获取预警信息失败，请稍后再试。";
    warningList.value = [];
  } finally {
    isWarningLoading.value = false;
  }
};

// 搜索天气
const searchWeather = () => {
  if (searchCity.value.trim()) {
    // 根据搜索框输入的城市名称获取天气信息
    getWeatherByManualCity(searchCity.value.trim());
    searchCity.value = '';
  } else {
    // 搜索框为空时显示提示信息
    ElMessage.warning('请输入城市名称');
  }
};

// 根据预警级别返回对应的Element UI类型
const getWarningType = (level) => {
  // 预警级别映射：红色(紧急)、橙色(严重)、黄色(较重)、蓝色(一般)
  const levelMap = {
    '红色': 'danger',
    '橙色': 'warning',
    '黄色': 'warning',
    '蓝色': 'info',
    '白色': 'info',
    '未知': 'info'
  };
  
  // 匹配预警级别，不区分大小写
  const matchedLevel = Object.keys(levelMap).find(
    key => level && level.toLowerCase().includes(key.toLowerCase())
  );
  
  return levelMap[matchedLevel] || 'info';
};
</script>

<style scoped>
.location-weather {
  /* 设置页面的最小高度、内边距、文本对齐方式和背景样式 */
  min-height: 100vh;
  padding: 20px;
  text-align: center;
  background-size: cover;
  background-position: center;
  background-attachment: fixed;
  position: relative;
}

.location-weather::before {
  /* 添加半透明遮罩层 */
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.7);
  z-index: 1;
}

.location-weather > * {
  /* 设置子元素的层级 */
  position: relative;
  z-index: 2;
}

h1 {
  /* 设置标题的颜色和阴影 */
  color: #333;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
}

.loading-container, .error-container {
  /* 设置加载和错误容器的样式 */
  padding: 20px;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 8px;
  margin: 20px auto;
  max-width: 500px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.spinner {
  /* 设置加载动画的样式 */
  width: 40px;
  height: 40px;
  border: 4px solid rgba(0, 0, 0, 0.1);
  border-left-color: #007BFF;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 15px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.search-container {
  /* 设置搜索容器的样式 */
  margin: 20px 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

.popular-cities {
  /* 设置热门城市容器的样式 */
  margin-top: 20px;
}

.city-tags {
  /* 设置热门城市标签容器的样式 */
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 8px;
  margin-top: 10px;
}

.el-tag {
  /* 设置标签的鼠标样式和过渡效果 */
  cursor: pointer;
  transition: transform 0.2s;
}

.el-tag:hover {
  /* 鼠标悬停时标签的缩放效果 */
  transform: scale(1.05);
}

.el-table, .warning-container, .no-warning-container {
  /* 设置表格、预警信息和无预警信息容器的样式 */
  margin-top: 20px;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 15px;
}

.warning-container h2 {
  /* 设置预警信息标题的样式 */
  margin-bottom: 15px;
  color: #333;
}

/* 预警信息的样式优化 */
.el-alert {
  /* 设置预警信息提示框的文本对齐方式和底部外边距 */
  text-align: left;
  margin-bottom: 10px;
}

.el-alert__content {
  /* 设置预警信息提示框内容的左内边距 */
  padding-left: 10px;
}
</style>